package com.fsh.lingsp.common.common.event.listener;


import com.fsh.lingsp.common.common.event.UserBlackEvent;
import com.fsh.lingsp.common.user.dao.UserDao;
import com.fsh.lingsp.common.user.domain.entity.User;
import com.fsh.lingsp.common.user.service.cache.UserCache;
import com.fsh.lingsp.common.websocket.adapter.WSAdapter;
import com.fsh.lingsp.common.websocket.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 作者：fsh
 * 日期：2024/03/06

 * 描述：用户拉黑事件监听器
 */
@Component
public class UserBlackListener {
    @Autowired
    private UserDao userDao;
    @Autowired
    private WebSocketService webSocketService;
    @Autowired
    private UserCache userCache;

    /**
     * 将 拉黑用户事件 推送给所有在线人员
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class
            ,phase = TransactionPhase.AFTER_COMMIT)
    public void sendMsgToAll(UserBlackEvent event){
        User user = event.getUser();
        webSocketService.sendMsgToAll(WSAdapter.buildBlackResp(user));
    }

    /**
     * 修改被拉黑用户的status ，0.正常 1拉黑
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class
            ,phase = TransactionPhase.AFTER_COMMIT)
    public void changeUserStatus(UserBlackEvent event){
        userDao.changeUserStatus(event.getUser().getId());
    }

    /**
     * 此时，已经有人进黑名单，那么黑名单的缓存需要清空。
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class
            ,phase = TransactionPhase.AFTER_COMMIT)
    public void clearBlackMap(UserBlackEvent event){
        userCache.clearBlackMap();
    }

}
